package com.xigua.basicsAndApplication;

import com.xigua.util.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: redis事务
 * @date 2022/1/1922:21
 */
public class TransactionDemo {
    public static void main(String[] args) {
        Jedis jedis = JedisUtil.getJedis();
        String userId = "abc";
        String key = keyFor(userId);
        jedis.setnx(key, String.valueOf(5));
        System.out.println(doubleAccount(jedis, userId));
        jedis.close();

    }

    public static int doubleAccount(Jedis jedis,String userId){
        String key = keyFor(userId);
        while (true){
            jedis.watch(key);
            int value = Integer.parseInt(jedis.get(key));
            value *=2;
            Transaction transaction = jedis.multi();
            transaction.set(key,String.valueOf(value));
            List<Object> res = transaction.exec();
            if (res != null){
                break;
            }
        }
        return Integer.parseInt(jedis.get(key));
    }

    public static String keyFor(String userId){
        return String.format("account_%s",userId);
    }



}
